package com.bz.xtcx.manager.mapper.provider;

import java.text.MessageFormat;

import com.bz.xtcx.manager.utils.WzStrUtil;
import org.springframework.util.StringUtils;

import com.bz.xtcx.manager.entity.SysUser;
import com.bz.xtcx.manager.vo.VoQuery;

public class SysUserProvider {

    public String findCount(VoQuery user){
        StringBuilder sql = new StringBuilder("select count(*) from `sys_user` where 1=1 ");
        sql.append(queryCondition(user));
        return sql.toString();
    }
    
    public String findByCondition(VoQuery user) {
        StringBuilder sql = new StringBuilder("select a.* from `sys_user` a ");
        if (WzStrUtil.isNotBlank(user.getUserType())) {
            sql.append(" inner join `sys_user_role` b on a.user_id = b.user_id ");
        }
        sql.append(" where 1=1 ");
        sql.append(queryCondition(user));
        return sql.toString();
    }
    
    StringBuilder queryCondition(VoQuery user) {
        StringBuilder sql = new StringBuilder();
        if(user != null) {
            if(WzStrUtil.isNotBlank(user.getStatus())) {
                sql.append(" and a.status = '"+user.getStatus()+"'");
            }
            if(WzStrUtil.isNotBlank(user.getUserType())) {
                sql.append(" and b.role_id = '"+user.getUserType()+"'");
            }
            if(WzStrUtil.isNotBlank(user.getObjName())) {
                sql.append(" and (");
                sql.append(" a.user_name like '%"+user.getObjName()+"%'");
                sql.append(" or a.email like '%"+user.getObjName()+"%'");
                sql.append(" or a.cellphone like '%"+user.getObjName()+"%'");
                sql.append(")");
            }
            
            /*if (user.getUserName() != null)
                sql.append(" and user_name like '%"+user.getUserName()+"%'");
            if (user.getCellphone() != null)
                sql.append(" and cellphone='"+user.getCellphone()+"'");
            if (user.getEmail() != null)
                sql.append(" and email='"+user.getEmail()+"'");*/
        }
        return sql;
    }
    
    public String addUserRoles(SysUser user){
        StringBuilder sql = new StringBuilder();
        sql.append("insert into `sys_user_role`(id, user_id, role_id, creater, create_time) values ");
        MessageFormat mf = new MessageFormat("(uuid(), #'{'id}, #'{'roles[{0}].id}, #'{'creater}, #'{'createTime} ),");
        for(int i = 0; i < user.getRoles().size(); i++) {
            sql.append(mf.format(new Object[]{i}));
        }
        if (WzStrUtil.isNotBlank(sql.toString()) && WzStrUtil.endsWith(sql.toString(), ",")) {
            sql.deleteCharAt(sql.length() - 1);
        }
//        System.out.println(sql);
        return sql.toString();
    }
}
